#include "head.h"

// 开启子进程
int starSon(int SonFd)
{
    while(true)
    {
        int NetFd;
        // 通过本地sockfd读取父进程新建的NetFd从而接受客户端消息
        printf("reading NetFd!\n");
        readNetFd(SonFd,&NetFd);
        printf("建立连接成功！\n");
        // 接收客户端消息
        netConversation(NetFd);
        // 给客户端发送指定文件
        fileSend(NetFd);

        close(NetFd);

        // 给父进程发消息，自己已完成任务
        pid_t pid = getpid();
        printf("pid:%d -> 完成任务！\n",pid);
        send(SonFd,&pid,sizeof(pid),0);
    }
    return 0;
}

// 与子进程通信
int netConversation(int NetFd)
{
    char *mess = "连接成功！";
    send(NetFd,mess,strlen(mess),0);

    sleep(2);

    return 0;
}

// 给客户端发送指定文件
int fileSend(int NetFd)
{
    char *FileName = "1.txt";
    int len = strlen(FileName);
    char buf[1000] = {0};

    int FileFd = open(FileName,O_RDONLY);
    // 获取文件属性
    struct stat stat_file;
    fstat(FileFd,&stat_file);

    // 发送文件长度
    send(NetFd,&stat_file.st_size,sizeof(off_t),0);

    send(NetFd,&len,sizeof(int),0);
    printf("len:%d\n",len);

    send(NetFd,FileName,len,0);
    printf("FileName:%s\n",FileName);


    if(FileFd < 0)
        printf("打开1.txt失败！\n");

    while(true)
    {
        int num = read(FileFd,buf,sizeof(buf));

        if(num == 0)
        {
            printf("文件已发送完毕！\n");
            send(NetFd,&num,sizeof(num),0);
            
            break;
        }

        send(NetFd,&num,sizeof(num),0);
        printf("num:%d\n",num);

        send(NetFd,buf,num,0);
        printf("buf:%s\n",buf);

        memset(buf,0,sizeof(buf));
    }

    return 0;
}












